package com.xuecheng.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.search.service.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;


@Slf4j
@Service
public class IndexServiceImpl implements IndexService {



 @Autowired
 RestHighLevelClient client;

 /**
  * 添加或更新课程索引文档
  *
  * @param indexName 目标索引名称（Elasticsearch索引名）
  * @param id        文档唯一标识符
  * @param object    需要存储的业务对象，会被序列化为JSON格式
  * @return Boolean 返回操作结果：true表示文档被成功创建/更新，false表示操作未成功
  */
 @Override
 public Boolean addCourseIndex(String indexName,String id,Object object) {
   // 将业务对象序列化为JSON字符串
   String jsonString = JSON.toJSONString(object);

   // 创建索引请求对象，指定索引名称和文档ID
   IndexRequest indexRequest = new IndexRequest(indexName).id(id);

   // 设置索引文档内容（JSON格式）
   indexRequest.source(jsonString,XContentType.JSON);

   IndexResponse indexResponse = null;
   try {
    // 执行索引操作并获取响应
    indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
   } catch (IOException e) {
    log.error("添加索引出错:{}",e.getMessage());
    e.printStackTrace();
    XueChengPlusException.cast("添加索引出错");
   }

   // 解析响应结果状态
   String name = indexResponse.getResult().name();
   System.out.println(name);

   // 判断操作结果是否为创建成功或更新成功
   return name.equalsIgnoreCase("created") || name.equalsIgnoreCase("updated");
 }

 @Override
 public Boolean updateCourseIndex(String indexName,String id,Object object) {

  String jsonString = JSON.toJSONString(object);
  UpdateRequest updateRequest = new UpdateRequest(indexName, id);
  updateRequest.doc(jsonString, XContentType.JSON);
  UpdateResponse updateResponse = null;
  try {
   updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
  } catch (IOException e) {
   log.error("更新索引出错:{}",e.getMessage());
   e.printStackTrace();
   XueChengPlusException.cast("更新索引出错");
  }
  DocWriteResponse.Result result = updateResponse.getResult();
  return result.name().equalsIgnoreCase("updated");

 }

 @Override
 public Boolean deleteCourseIndex(String indexName,String id) {

  //删除索引请求对象
  DeleteRequest deleteRequest = new DeleteRequest(indexName,id);
  //响应对象
  DeleteResponse deleteResponse = null;
  try {
   deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
  } catch (IOException e) {
   log.error("删除索引出错:{}",e.getMessage());
   e.printStackTrace();
   XueChengPlusException.cast("删除索引出错");
  }
  //获取响应结果
  DocWriteResponse.Result result = deleteResponse.getResult();
  return result.name().equalsIgnoreCase("deleted");
 }
}
